import { ref, reactive } from 'vue'
import { goDialog, httpErrorHandle } from '@/utils'
import { DialogEnum } from '@/enums/pluginEnum'
import { companyListApi, companyDeleteApi } from '@/api/path'
import { ResultEnum } from '@/enums/httpEnum'

import bus from '@/utils/bus'

// 数据初始化
export const useDataListInit = () => {
  const loading = ref(true)

  const paginat = reactive({
    // 当前页数
    page: 1,
    // 每页值
    limit: 12,
    // 总数
    count: 10
  })

  const list = ref<any[]>([])

  // 数据请求
  const fetchList = async () => {
    loading.value = true
    const res = await companyListApi({
      page: paginat.page,
      limit: paginat.limit
    })
    if (res && res.data) {
      // const { count } = res as any // 这里的count与data平级，不在Response结构中
      // paginat.count = count
      list.value = res.data || []
      setTimeout(() => {
        loading.value = false
      }, 500)
      return
    }
    httpErrorHandle()
  }

  // 修改页数
  const changePage = (_page: number) => {
    paginat.page = _page
    fetchList()
  }

  // 修改大小
  const changeSize = (_size: number) => {
    paginat.limit = _size
    fetchList()
  }

  // 删除处理
  const deleteHandle = (cardData: any) => {
    goDialog({
      type: DialogEnum.DELETE,
      promise: true,
      onPositiveCallback: () =>
        new Promise(res => {
          res(
            companyDeleteApi({
              userID: cardData.userID
            })
          )
        }),
      promiseResCallback: (res: any) => {
        if (res.code === ResultEnum.SUCCESS) {
          window['$message'].success(window['$t']('global.r_delete_success'))
          fetchList()
          return
        }
        httpErrorHandle()
      }
    })
  }

  // 立即请求
  fetchList()

  bus.on('refresh-list', () => {
    fetchList()
  })

  return {
    loading,
    paginat,
    list,
    fetchList,
    changeSize,
    changePage,
    deleteHandle
  }
}
